﻿using OperationPlugins.Applications.Remoting;
using System;

namespace OperationPlugins.Applications
{
    internal abstract class ProxyBase
    {
        internal ProxyBase(ApplicationInstanceImpl instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            Instance = instance;
        }

        protected ApplicationInstanceImpl Instance { get; private set; }

        protected SandboxContext PrepareRequest()
        {
            InitializeOperationPluginsContext();
            
            return new SandboxContext
            {
                OperationPluginsContext = OperationPluginsContext.Current,
                ApplicationRequestContext = Instance.Context,
                ApplicationDataContext = ApplicationManager.ApplicationDataContext
            };
        }

        private void InitializeOperationPluginsContext()
        {
            if (string.IsNullOrEmpty(Instance.Context.Headers.OperationId) == false)
            {
                OperationPluginsContext.Current.CurrentActionOperation = new OperationId(Instance.Context.Headers.OperationId);
            }

            if (string.IsNullOrEmpty(Instance.Context.Headers.BranchId) == false)
            {
                OperationPluginsContext.Current.CurrentActionBranch = new BranchId(Instance.Context.Headers.BranchId);
            }
        }

    }
}
